<?php

/**
 * @author Xinpow
 * @copyright 2012/03/14
 * @name 验证码
 * 
 * @param $code_type    0,1,2,3分别为英文,数字,中文,数英验证码
 * @param $code_len     验证码长度
 * 
 * 验证码类,支持中文验证码,同时需要MD类函数支持.PHP5+版本
 * 使用方法:直接实例化类
 * 判断方法:判断$_SESSION['v_code']
 */
 
 class vcode{
    
    protected $vcode_str, $code_len, $vsession, $code_type;
    
    public function __construct($code_type = 3, $code_len = 6){
        if(!session_start())
            session_start();
        header("content-type:image/png");
        if($code_type < 0 || $code_type > 3) $code_type = 3;
        if($code_len < 2) $code_len = 2;
        switch($code_type){
            case 0:
                $vcode_str = 'abcdefghizklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            case 1:
                $vcode_str = '0123456789';
                break;
            case 2:
                $vcode_str = '你我他她它苦逼神马强大抢答墙哒龙猪牛马狗羊鼠猫蛇电话脑器气骑啊阿吖嗄锕吧不把被帮比别并微软脸书数输术';
                break;
            default:
                $vcode_str = '0123456789abcdefghizklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        }
        $this->vsession  = null;
        $this->code_len  = $code_len;
        $this->code_type = $code_type;
        $this->vcode_str = $vcode_str;
        $this->explodeStr();
        $this->imageFrame();
    }
    
    protected function explodeStr(){
        $this->vcode_str = preg_split('/(?<!^)(?!$)/u', $this->vcode_str);
        $_ = array_rand($this->vcode_str, $this->code_len);
        foreach($_ as $value){
            $this->vsession .= $this->vcode_str[$value];
        }
    }
    
    protected function imageFrame(){
        if($this->code_type != 2)
            $img     = ImageCreate($this->code_len * 12, 30);
        else
            $img     = ImageCreate($this->code_len * 15, 30);
        $red     = ImageColorAllocate($img, 0, 0, 0);
        $bgcolor = ImageColorAllocate($img, 0, 0, 0);
        //背景色透明
        $bgcolortrans = ImageColorTransparent($img, $bgcolor);
        if($this->code_type != 2)
            ImageString($img, 5, 10, 5, $this->vsession, $red);
        else
            imagettftext($img, 10, rand(-5,5), 5, 18, $red, 'simsun.ttc', $this->vsession);
        ImagePng($img);
        ImageDestroy($img);
        $_SESSION['v_code'] = $this->vsession;
    }
    
 }
 new vcode(2, 10);
?>